package com.lxujia.ruankao.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;

import com.lxujia.ruankao.BuildConfig;
import com.lxujia.ruankao.R;
import com.lxujia.ruankao.model.DbInitModel;
import com.lxujia.ruankao.util.LogUtil;
import com.lxujia.ruankao.util.PermissionHelper;

import org.litepal.LitePal;

import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class WelcomeActivity extends Activity {
    private final static String TAG = "WelcomeActivity";
    private Context mContext;
    private PermissionHelper mPermissionHelper;
    private View mLoadingView;

    private boolean mThirdLog = BuildConfig.LOG_DEBUG;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_welcome);

        // 当系统为6.0以上时，需要申请权限
        mPermissionHelper = new PermissionHelper(this);
        mPermissionHelper.setOnApplyPermissionListener(new PermissionHelper.OnApplyPermissionListener() {
            @Override
            public void onAfterApplyAllPermission() {
                LogUtil.i(TAG, "All of requested permissions has been granted, so run app logic.");
                runApp();
            }
        });
        if (Build.VERSION.SDK_INT < 23) {
            // 如果系统版本低于23，直接跑应用的逻辑
            LogUtil.d(TAG, "The api level of system is lower than 23, so run app logic directly.");
            runApp();
        } else {
            // 如果权限全部申请了，那就直接跑应用逻辑
            if (mPermissionHelper.isAllRequestedPermissionGranted()) {
                LogUtil.d(TAG, "All of requested permissions has been granted, so run app logic directly.");
                runApp();
            } else {
                // 如果还有权限为申请，而且系统版本大于23，执行申请权限逻辑
                LogUtil.i(TAG, "Some of requested permissions hasn't been granted, so apply permissions first.");
                mPermissionHelper.applyPermissions();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mPermissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mPermissionHelper.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 跑应用的逻辑
     */
    private void runApp() {
        showLoadingView();
    }

    private void showLoadingView() {
        DbInitModel dbInitModel = LitePal.where("initSuccess == 1").findFirst(DbInitModel.class);
        mLoadingView = findViewById(R.id.rl_progress_bar);
        if (dbInitModel == null || dbInitModel.getInitSuccess() != 1) {
            // 数据库未初始化完成
            LogUtil.d(TAG, "showLoadingView");

            mLoadingView.setVisibility(View.VISIBLE);

            final ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(1);
            scheduledExecutor.scheduleWithFixedDelay(new TimerTask() {
                @Override
                public void run() {
                    DbInitModel initModel = LitePal.where("initSuccess == 1").findFirst(DbInitModel.class);
                    Log.d(TAG, "WelcomeActivity initModel = " + initModel);
                    if (initModel != null && initModel.getInitSuccess() == 1) {
                        startMainActivity();
                        scheduledExecutor.shutdown();
                    }
                }
            }, 1, 1, TimeUnit.SECONDS);
        } else {
            mLoadingView.setVisibility(View.GONE);
            startMainActivity();
        }
    }

    private void startMainActivity() {
        Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
        startActivity(intent);
        WelcomeActivity.this.finish();
        Log.d(TAG, "WelcomeActivity finish");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
